<template>
  <div class="app-container">
    <el-card class="box-card">
      <h4>{{$t('Basic_Information')}}</h4>
      <el-form ref="goodsForm" :rules="rules" :model="packageForm" label-width="150px">
<!--        <el-form-item :label="$t('选择区域')"  v-if="!shop">
          <el-select v-model="regionMultipleData.countryId"   :placeholder="$t('请选择')">
            <el-option
                v-for="country in regionMultiple.countrys"
                :label="country.nameCn || country.nameEn"
                :value="country.id">
            </el-option>
          </el-select>

          <el-select v-model="regionMultipleData.provinceId" filterable @change="(value) => loadingProvince(value)" :placeholder="$t('请选择')">
            <el-option
                v-for="province in regionMultiple.provinces"
                :label="province.nameCn || province.nameEn"
                :value="province.id">
            </el-option>
          </el-select>

          <el-select v-model="regionMultipleData.cityId" filterable multiple @change="changeCityMultiple" :placeholder="$t('请选择')">
            <el-option
                v-for="city in regionMultiple.citys"
                :label="city.nameCn || city.nameEn"
                :value="city.id">
            </el-option>
          </el-select>
        </el-form-item>-->

        <el-form-item :label="$t('选择区域')" prop="regionId" v-if="!shop">
          <el-button icon="el-icon-position" type="primary" plain1 size="mini" @click="addRegion">{{$t('添加区域')}}</el-button>
          <p v-for="(item, i) in regionList">
            <el-tag>{{ $t('序号') + (i+1) }}:</el-tag>
            <el-select v-model="regions[i].countryId" filterable @change="(value) => changeCountry(i, value)" :placeholder="$t('请选择')">
              <el-option
                v-for="country in item.countrys"
                :label="country.nameCn || country.nameEn"
                :value="country.id">
              </el-option>
            </el-select>

            <el-select v-model="regions[i].provinceId" filterable @change="(value) => changeProvince(i, value)" :placeholder="$t('请选择')">
              <el-option
                v-for="province in item.provinces"
                :label="province.nameCn || province.nameEn"
                :value="province.id">
              </el-option>
            </el-select>

            <el-select v-model="regions[i].cityId" filterable @change="(value) => changeCity(i, regions[i], value)" :placeholder="$t('请选择')">
              <el-option
                v-for="city in item.citys"
                :label="city.nameCn || city.nameEn"
                :value="city.id">
              </el-option>
            </el-select>

            <el-button type="danger" icon="el-icon-delete" plain1 circle size="mini" @click="deleteRegion(i)"></el-button>
            <el-row>
              <el-col :span="2">{{$t('税率类型')}}：</el-col>
              <el-col :span="22">
                <el-checkbox-group v-model="regions[i].taxTypes">
                  <el-checkbox v-for="tax in item.taxTypes" :label="tax.id" :key="tax.id">{{tax.code}}</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </p>
        </el-form-item>
        <el-form-item :label="$t('Category')" prop="categoryId">
          <el-cascader :options="categoryList" v-model="categoryIds" expand-trigger="hover" @change="handleCategoryChange" :placeholder="$t('请选择')"/>
        </el-form-item>

        <el-form-item :label="$t('套餐编号')" prop="packageNumber">
          <el-input  v-model="packageForm.packageNumber" disabled/>
        </el-form-item>
        <el-form-item :label="$t('套餐名称')" prop="packageName">
          <el-input v-model="packageForm.packageName"/>
        </el-form-item>
        <el-form-item :label="$t('缩写')" prop="subhead">
          <el-input v-model="packageForm.subhead"/>
        </el-form-item>
        <el-form-item :label="$t('金额')" prop="amount">
          <el-input v-model="packageForm.amount"/>
        </el-form-item>
        <!-- <el-form-item :label="$t('计量单位')" prop="unit">
          <el-input v-model="packageForm.unit"/>
        </el-form-item> -->
        <el-form-item :label="$t('套餐简介')">
          <el-input v-model="packageForm.packageIntroduction"/>
        </el-form-item>
        <el-form-item :label="$t('套餐图片')" prop="packageImg">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadPicUrl"
            :on-remove="handleGoodsPicRemove"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="packageForm.packageImg" :src="packageForm.packageImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <label v-if="packageForm.packageImg" class="el-upload-list__item-status-label avatar-uploader__status_label" @click.stop="handleGoodsPicRemove()"><i class="el-icon-delete"></i></label>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('Gallery')">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :limit="5"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif,.mp4"
            list-type="picture-card">
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('套餐详情介绍')">
          <el-input type="textarea" :init="editorInit" v-model="packageForm.packageDetailsIntroduce"/>
        </el-form-item>
        <el-form-item :label="$t('操作说明')">
          <el-input type="textarea" v-model="packageForm.operationExplain"></el-input>
        </el-form-item>
        <el-form-item :label="$t('Goods_tax_type')" v-if="shop">
          <el-checkbox-group v-model="regions[0].taxTypes">
            <el-checkbox v-for="tax in shopTaxTypes" :label="tax.id" :key="tax.id">{{tax.code}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item :label="$t('套餐营业时间')" prop="packageNumber">
          <el-descriptions class="margin-top" :title="$t('说明：如不营业请设置服务时间为 00:00:00-00:00:00')" :column="2" border>
            <el-descriptions-item v-for="o in 7" :span="1">
              <template slot="label">
                <el-tag :style="{width:'80px','text-align':'center'}" type="info">{{weeksTimeMap[o] }}</el-tag>
              </template>
              <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="weeksTime[o-1]"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
              </el-time-picker>
            </el-descriptions-item>
            <template slot="extra">
              <el-button type="primary" size="small" @click="showDatePicker"> {{!showDatepicker?$t('添加特殊日期'):$t('关闭') }}</el-button>
              <el-date-picker
                  :clearable="false"
                  value-format="yyyy-MM-dd"
                  @change="handleChangePicker"
                  v-model="selectedDate"
                  v-if="showDatepicker" >
              </el-date-picker>
            </template>
            <!--              特殊日期-->
            <el-descriptions-item  v-for="o in this.special.length" :span="1">
              <template slot="label">
                <el-tag effect="dark" type="warning">{{special[o-1].specialDate }}</el-tag>
              </template>
              <el-time-picker
                  format="HH:mm:ss" value-format="HH:mm:ss"
                  is-range
                  :clearable="false"
                  v-model="special[o-1].specialTime"
                  range-separator="-"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')"
                  :placeholder="$t('选择时间')">
              </el-time-picker>
              <el-button :style="{'margin-left':'5px'}" @click="handleSpecialTimeDeleted(o-1)" size="mini" type="danger" icon="el-icon-delete" ></el-button>
            </el-descriptions-item>
          </el-descriptions>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <el-card class="box-card">
      <h4>{{$t('Other_information')}}</h4>
      <el-form ref="others" :rules="rules" :model="goods" label-width="150px">
        <el-form-item :label="$t('Merchandise_label')">
          <el-checkbox :value="true" v-model="goods.isNew">{{$t('New_product')}}</el-checkbox>
          <el-checkbox :value="true" v-model="goods.isHot">{{$t('Recommendation')}}</el-checkbox>
        </el-form-item>
        <el-form-item :label="$t('Services')" prop="isReturn">
          <el-radio-group v-model="goods.isReturn">
            <el-radio :label="true">{{$t('Refundable')}}</el-radio>
            <el-radio :label="false">{{$t('Non-refundable')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('Delivery_Services')" prop="distributionFee">
          <el-radio-group v-model="goods.isDistribution">
            <el-radio :label="false">{{$t('Delivery_Free')}}</el-radio>
            <el-radio :label="true" >{{$t('Delivery_Fee')}}</el-radio>
          </el-radio-group>
          <el-input v-show="goods.isDistribution" v-model="goods.distributionFee"></el-input>
        </el-form-item>
      </el-form>
    </el-card> -->

    <!-- <el-card class="box-card">
      <h4>{{$t('Merchandise_Parameters')}}</h4>
      <el-button icon="el-icon-circle-plus" :plain1="true" type="primary" @click="handleAttributeShow">{{$t('Add')}}</el-button>
      <el-table :data="attributes">
        <el-table-column property="attribute" :label="$t('Merchandise_parameter_names')"/>
        <el-table-column property="value" :label="$t('Merchandise_parameter_values')"/>
        <el-table-column align="center" :label="$t('Operate')" width="100" class-name="small-padding fixed-width">
          <template slot="header" slot-scope="{row}">
            {{$t('Operate')}}
            <i class="el-icon-s-tools" style="color: #d35e32"></i>
          </template>
          <template slot-scope="scope">
            <el-button icon="el-icon-delete" plain1 type="danger" size="mini" @click="handleAttributeDelete(scope.row)">{{$t('Delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="attributeVisiable" :title="$t('Set_merchandise_parameter_values')">
        <el-form ref="attributeForm" :model="attributeForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item :label="$t('Merchandise_parameter_names')" prop="attribute">
            <el-input v-model="attributeForm.attribute"/>
          </el-form-item>
          <el-form-item :label="$t('Merchandise_parameter_values')" prop="value">
            <el-input v-model="attributeForm.value"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-error" plain1 @click="attributeVisiable = false">{{$t('Cancel')}}</el-button>
          <el-button icon="el-icon-success" plain1 type="primary" @click="handleAttributeAdd">{{$t('Confirm')}}</el-button>
        </div>
      </el-dialog>
    </el-card> -->

    <div class="op-container" style="margin-top: 30px;">
      <el-button icon="el-icon-error" plain1 @click="handleCancel">{{$t('Cancel')}}</el-button>
      <el-button icon="el-icon-s-promotion" plain1 type="primary" @click="handleCreate">{{$t('新增套餐')}}</el-button>
    </div>
  </div>
</template>

<script>
  import { publishGoods, listCatAndBrand, batchCreate } from '@/api/goods'
  import { listCountryRegion, listSubRegion } from '@/api/region'
  import { createStorage, uploadPath,createMinioStorage } from '@/api/storage'
  import Editor from '@tinymce/tinymce-vue'
  import { MessageBox } from 'element-ui'
  import { getToken } from '@/utils/auth'
  import { allForPerm } from '@/api/shop'
  import { allMerchandise } from '@/api/merchandise'
  import { findByRegionId } from '@/api/tax'
  import store from '@/store'
  import {addPackage,generatePackageSn} from "@/api/package"

  export default {
    name: 'packageCreate',
    components: { Editor },
    data() {
      const validateDouble = (rule, value, callback) => {
        console.log('value' + value)
        if (!value || !/^[0-9,.]*$/.test(value)) {
          callback(new Error(this.$t('Sale_price_must_be_a_number')))
        } else {
          callback()
        }
      }

      const validateRegion = (rule, value, callback) => {
        // 如果是店铺登录则退出不校验
        if (this.shop) {
          callback()
          return
        }

        if (this.regions.length  == 0) {
          callback(new Error(this.$t('请选择完整的区域信息')))
        }

        let selectedCityIds = [];
        for (let i = 0; i < this.regions.length; i++) {
          let region = this.regions[i]
          let cityId = region.cityId
          if (!cityId) {
            callback(new Error(this.$t('请选择完整的区域信息')))
            return
          } else {
            for (let j = 0; j < selectedCityIds; j++) {
              if (cityId == selectedCityIds[j]) {
                callback(new Error(this.$t('请勿选择重复的区域信息')))
                return
              }
            }
            selectedCityIds.push(cityId)
          }
        }

        callback()
      }

      const validateCategory = (rule, value, callback) => {
        if (this.categoryIds.length == 0) {
          callback(new Error(this.$t('Category_cannot_be_empty')))
        } else {
          callback()
        }
      }

      const weeksTimeMap={
        1: this.$t('星期一'),
        2: this.$t('星期二'),
        3: this.$t('星期三'),
        4: this.$t('星期四'),
        5: this.$t('星期五'),
        6: this.$t('星期六'),
        7: this.$t('星期日')
      }

      return {
        //套餐营业时间
        weeksTimeMap,
        weeksTime:[],
        selectedDate: new Date(),
        showDatepicker: false,
        special:[],
        //套餐列表
        packageForm: {
            id: undefined,
            categoryId: undefined,
            packageNumber: undefined,
            packageName: undefined,
            subhead: undefined,
            amount:undefined,
            packageIntroduction: undefined,
            packageImg: undefined,
            disseminateGallery: undefined,
            packageDetailsIntroduce: undefined,
            operationExplain: undefined,
            number:1,
            salesVolume:0,
            weeksTime:[],
            special:[],
        },
        gallery: [],
        // 当前店铺
        shop: store.state.user.shop,
        shopRegions: store.state.user.shopRegions,
        shops:[],
        uploadPath,
        limited: false,
        vipPriceForm:{},
        stepPriceForms:[{
        }],
        moneyOfPriceForms:[{
        }],
        newKeywordVisible: false,
        newKeyword: '',
        keywords: [],
        galleryFileList: [],
        categoryList: [],
        //第一条
        regionMultiple : {
          countrys: [],
          provinces: [],
          citys: [],
          taxTypes: []
        },
        regionMultipleData : {
          countryId: undefined,
          provinceId: undefined,
          cityId: [],
          taxTypes: []
        },
        regionList: [],
        regionIndex:0,
        brandList: [],
        categoryIds: [],
        goods: { picUrl: '',priceType:"1",gallery: [],goodsType:1, isReturn:false, isDistribution: false, taxTypes: [] },
        regions: [],
        specVisiable: false,
        specForm: { specification: '', value: '', picUrl: '' },
        specifications: [],
        productVisiable: false,
        productForm: {
          id: 0,
          specifications: [],
          price: 0.0,
          number: 0,
          url: '',
          tax:0.0,
          taxTypes:[]
        },
        attributeVisiable: false,
        attributeForm: { attribute: '', value: '' },
        attributes: [],
        rules: {
          packageNumber:[
            { required: true, message: this.$t('Merchandise_ID_must_not_be_empty'), trigger: 'blur' }
          ],
          amount: [{ required: true, message: this.$t('Sale_price_cannot_be_empty'), trigger: 'blur' }],
          packageName: [{ required: true, message: this.$t('Merchandise_name_must_not_be_empty'), trigger: 'blur' }],
          regionId: [{ trigger: 'change',validator: validateRegion }],
          categoryId: [{ required: true, message: this.$t('Category_cannot_be_empty'), trigger: 'change',validator: validateCategory }],
          packageImg: [{ required: true, message: this.$t('Advertisement_picture_cannot_be_empty'), trigger: 'change' }],
        },
        productRules:{
          number: [
            { required: true, message: this.$t('Stock_amount_cannot_be_empty'), trigger: 'blur' },
            { type: 'number', message: this.$t('Stock_amount_must_be_a_number'), trigger: 'blur' }
          ],
          sellPrice: [{ required: true, message: this.$t('Sale_price_cannot_be_empty'), trigger: 'change' },
            { required: true,validator: validateDouble, trigger: 'change' }],
          costPrice: [{ required: true, message: this.$t('Buy-in_cost_cannot_be_empty'), trigger: 'change' },
            { required: true,validator: validateDouble, trigger: 'change' }],
        },
        editorInit: {
          language: 'zh_CN',
          convert_urls: false,
          plugins: [
            'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
          ],
          toolbar: [
            'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
            'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
          ],
          images_upload_handler: function(blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('file', blobInfo.blob())
            createMinioStorage(formData)
              .then(res => {
                success(res.data.data.url)
              })
              .catch(() => {
                failure(this.$t('Upload_failed_please_reupload'))
              })
          }
        },
        taxes:[{
          value:0,
          type:1,
          enable:false
        },{
          value:0,
          type:2,
          enable:false
        },{
          value:0,
          type:3,
          enable:false
        }],
        taxTypeData: [
          {
            value: "GST",
            label: "GST"
          },
          {
            value: "PST",
            label: "PST"
          }
        ],
        // 店铺税类型
        shopTaxTypes: [],
        shopIds:[],

        accessoryVisiable: false,
        accessoryForm: {},
        accessories: [],
        accessoryRules: {
          groupName: [{ required: true, message: this.$t('辅料组名不能为空'), trigger: 'blur' }],
          merchandiseId: [{ required: true, message: this.$t('辅料名不能为空'), trigger: 'change' }],
          price: [{ required: true, message: this.$t('辅料价格不能为空'), trigger: 'blur' }],
        },
        merchandise: []

      }
    },
    computed: {
      headers() {
        return {
          'X-Litemall-Admin-Token': getToken()
        }
      }
    },
    created() {
      this.init()
      this.generatePackageSn()

      this.loadingFirstRegion()
      this.handleShow();
    },
    methods: {
      //套餐营业时间
      handleShow(){
        for (let i = 0; i < 7; i++) {this.weeksTime.push(['23:59:59', '23:59:59']);}
        this.packageForm.weeksTime=this.weeksTime
        //this.special=this.packageForm.special
      },
      showDatePicker() {
        this.showDatepicker = !this.showDatepicker;
      },
      //选择了某一天
      handleChangePicker(date){
        const newDate = { specialDate: date, specialTime: ['23:59:59','23:59:59'] };
        const hasDuplicate = this.special.some(item => item.specialDate === newDate.specialDate);
        if (!hasDuplicate) {
          this.special.push(newDate);
          this.special.sort((a, b) => {
            const dateA = new Date(a.specialDate);
            const dateB = new Date(b.specialDate);
            return dateA - dateB;
          });
        } else {
          // 如果存在相同的 specialDate 值，进行相应的处理
          this.$notify({
            title: '警告',
            message: '已存在相同的日期，无法添加重复项',
            type: 'warning'
          });
        }
      },
      handleSpecialTimeDeleted(index){
        this.special.splice(index, 1);
      },
      init: function() {
        listCatAndBrand().then(response => {
          this.categoryList = response.data.data.categoryList
        })

        allForPerm().then(response=>{
          this.shops = response.data.data.list
        })

        // 初始化店铺税务类型
        if (this.shopRegions && this.shopRegions.length == 3) {
          let countryId = this.shopRegions[0].id
          let provinceId = this.shopRegions[1].id
          let cityId = this.shopRegions[2].id

          let region = {
            countryId: countryId,
            provinceId: provinceId,
            cityId: cityId,
            taxTypes: []
          }
          this.regions.push(region)

          findByRegionId(countryId, provinceId, cityId).then(response=>{
            this.shopTaxTypes = response.data.data.list
          })
        }
      },
      // 生成商品代码方法
      generatePackageSn() {
        generatePackageSn().then(response=>{
          this.packageForm.packageNumber = response.data.data
        })
      },
      //加载第一条数据
      loadingFirstRegion () {
        listCountryRegion().then(response=>{
          this.regionMultiple.countrys = response.data.data.list

          let query = {
            id: this.regionMultiple.countrys[0].id,
            type: 2
          }
          listSubRegion(query).then(response=>{
            this.regionMultiple.provinces = response.data.data.list
          })

          this.regionMultipleData.countryId = this.regionMultiple.countrys[0].id;
          //this.regionMultipleData.provinceId = this.regionMultiple.provinces[0].id;
        })
      },
      loadingProvince (value) {
        this.regionMultipleData.cityId = []
        let query = {
          id: value,
          type: 2
        }
        listSubRegion(query).then(response=>{
          this.regionMultiple.citys = response.data.data.list
        })
      },
      changeCityMultiple (value) {
        this.regionIndex += 1;
        this.regionList[this.regionIndex-1] = ({countrys: [], provinces: [], citys: [], taxTypes: []})
        this.regionList[this.regionIndex-1].countrys = this.regionMultiple.countrys.slice();
        this.regionList[this.regionIndex-1].provinces = this.regionMultiple.provinces.slice();
        this.regionList[this.regionIndex-1].citys = this.regionMultiple.citys.slice();

        this.regions[this.regionIndex-1] = {
          countryId: undefined,
          provinceId: undefined,
          cityId: undefined,
          taxTypes: []
        }
        this.regions[this.regionIndex-1].countryId = JSON.parse(JSON.stringify(this.regionMultipleData.countryId));
        this.regions[this.regionIndex-1].provinceId = JSON.parse(JSON.stringify(this.regionMultipleData.provinceId));
        this.regions[this.regionIndex-1].cityId = JSON.parse(JSON.stringify(value[this.regionIndex-1]));
        findByRegionId(this.regionMultipleData.countryId, this.regionMultipleData.provinceId, value[this.regionIndex-1]).then(response=>{
          this.regionList[this.regionIndex-1].taxTypes = response.data.data.list
        })

        console.log('this.regionList[this.regionIndex-1]',this.regionList)

      },
      addRegion () {
        if(this.regionList.length==0){
          let region = {
            countrys: [],
            provinces: [],
            citys: [],
            taxTypes: []
          }

          listCountryRegion().then(response=>{
            region.countrys = response.data.data.list
          })

          this.regionList.push(region)

          let regionData = {
            countryId: undefined,
            provinceId: undefined,
            cityId: undefined,
            taxTypes: []
          }

          this.regions.push(regionData)
        }

        //复制上一份的数据
        else{
          if(this.regions[0].countryId==undefined){
            this.$notify({
              title: "提示",
              message: "请完善第一条数据",
              type: "warning",
            });
            return;
          }
          this.regionList.push(Object.assign({}, this.regionList[this.regionList.length-1]))
          this.regions.push(Object.assign({}, this.regions[this.regions.length-1]))
        }

      },
      deleteRegion (index) {
        this.regionIndex--;
        const idToRemove = this.regions[index].cityId;
        this.regionMultipleData.cityId = this.regionMultipleData.cityId.filter(id => id!== idToRemove);
        this.regionList.splice(index, 1)
        this.regions.splice(index, 1)
      },
      changeCountry (index, value) {
        this.regionList[index].provinces = []
        this.regionList[index].citys = []
        this.regionList[index].taxTypes = []
        this.regions[index].provinceId = undefined
        this.regions[index].cityId = undefined

        let query = {
          id: value,
          type: 2
        }
        listSubRegion(query).then(response=>{
          this.regionList[index].provinces = response.data.data.list
        })
      },

      changeProvince (index, value) {
        this.regionList[index].citys = []
        this.regionList[index].taxTypes = []
        this.regions[index].cityId = undefined

        let query = {
          id: value,
          type: 2
        }
        listSubRegion(query).then(response=>{
          this.regionList[index].citys = response.data.data.list
        })
      },

      changeCity (index, region, value) {
        let countryId = region.countryId
        let provinceId = region.provinceId
        let cityId = region.cityId
        findByRegionId(countryId, provinceId, cityId).then(response=>{
          this.regionList[index].taxTypes = response.data.data.list
        })
      },
      handleCategoryChange(value) {
        this.packageForm.categoryId = value[value.length - 1]
      },
      handleCancel: function() {
        if (this.shop) {
          this.$router.push({ path: '/goods/shop_list' })
        } else {
          this.$router.push({ path: '/goods/package' })
        }
      },
      handleClose(tag) {
        this.keywords.splice(this.keywords.indexOf(tag), 1)
        this.goods.keywords = this.keywords.toString()
      },
      uploadPicUrl: function(response) {
        this.packageForm.packageImg = response.data.url
        // 上传成功后，手动验证一次表单
        this.$refs.goodsForm.validateField('packageImg');
      },
      uploadOverrun: function() {
        this.$message({
          type: 'error',
          message: this.$t('File_upload_exceeded_maximum_value!_Max._5_photos')
        })
      },
      handleGalleryUrl(response, file, fileList) {
        if (response.errno === 0) {
          this.gallery.push(response.data.url)
        }
      },
      uploadSpecPicUrl: function(response) {
        this.specForm.picUrl = response.data.url
      },
      handleSpecificationShow() {
        this.specForm = { specification: '', value: '', picUrl: '' }
        this.specVisiable = true
      },
      handleAccessoryShow(){
/*        if(!this.goods.shopId){
          this.$notify.error({
            title: this.$t('失败'),
            message: this.$t('请先选择门店')
          })
        }else{*/
        allMerchandise().then(response=>{
          this.merchandise = response.data.data
          this.accessoryForm = { groupName: '', name: '', price: 0.00 }
          this.accessoryVisiable = true
        })
        // }
      },
      handleSpecificationAdd() {
        var index = this.specifications.length - 1
        for (var i = 0; i < this.specifications.length; i++) {
          const v = this.specifications[i]
          if (v.specification === this.specForm.specification) {
            index = i
          }
        }

        this.specifications.splice(index + 1, 0, this.specForm)
        this.specVisiable = false

      },
      handleAccessoryAdd(){
        this.$refs['accessoryForm'].validate((valid) => {
          if (valid) {
            var index = this.accessories.length - 1
            for (var i = 0; i < this.accessories.length; i++) {
              const v = this.accessories[i]
              if (v.accessories === this.accessoryForm.name) {
                index = i
              }
            }

            this.accessories.splice(index + 1, 0, this.accessoryForm)
            this.accessoryVisiable = false
          }
        })

      },
      handleSpecificationDelete(row) {
        const index = this.specifications.indexOf(row)
        this.specifications.splice(index, 1)
      },
      handleAccessoryDelete(row){
        const index = this.accessories.indexOf(row)
        this.accessories.splice(index, 1)
      },

      handleAttributeShow() {
        this.attributeForm = {}
        this.attributeVisiable = true
      },
      handleAttributeAdd() {
        this.attributes.unshift(this.attributeForm)
        this.attributeVisiable = false
      },
      handleAttributeDelete(row) {
        const index = this.attributes.indexOf(row)
        this.attributes.splice(index, 1)
      },
      handleStepAdd(row){
        this.stepPriceForms.push({
          number:undefined,
          price:undefined
        })
      },
      handleStepDelete(scope){
        if(this.stepPriceForms.length > 1){
          this.stepPriceForms.splice(scope.$index,1)
        }else{
          this.stepPriceForms[0] = {
            number:undefined,
            price:undefined
          }
        }
      },
      handleMoneyOfAdd(row){
        this.moneyOfPriceForms.push({
          maxPrice:undefined,
          minusPrice:undefined
        })
      },
      handleMoneyOfDelete(scope){
        if(this.moneyOfPriceForms.length > 1){
          this.moneyOfPriceForms.splice(scope.$index,1)
        }else{
          this.moneyOfPriceForms[0] = {
            maxPrice:undefined,
            minusPrice:undefined
          }
        }
      },
      handleRemove: function(file, fileList) {
        for (var i = 0; i < this.gallery.length; i++) {
          // 这里存在两种情况
          // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
          //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
          // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
          var url
          if (file.response === undefined) {
            url = file.url
          } else {
            url = file.response.data.url
          }

          if (this.gallery[i] === url) {
            this.gallery.splice(i, 1)
          }
        }
      },

      handleCreate: function() {
        this.packageForm.disseminateGallery =  this.gallery.join(',');

        this.packageForm.special = this.special;
        const finalGoods = {
          lumierePackage: this.packageForm,
          regions: this.regions,
          specifications: this.specifications,
          attributes: this.attributes,
          shopIds: this.shopIds,
          accessories: this.accessories
        }
        this.taxes.forEach(tax=>{
          if(tax.enable && this.productForm.taxTypes.indexOf(tax) < 0){
            this.goods.taxTypes.push(tax.type)
          }
        })
        if(this.goods.priceType == "1"){
          finalGoods.vipPrice = this.vipPriceForm
        }else if(this.goods.priceType == "2"){
          finalGoods.ladderPrices = this.stepPriceForms
        }else if(this.goods.priceType == "3"){
          finalGoods.maxMinusPrices = this.moneyOfPriceForms
        }
        if(this.goods.shopId){
          this.shops.forEach((shop)=>{
            if(this.goods.shopId == shop.id){
              this.goods.shopName = shop.name
            }
          })
        }
        console.log(finalGoods)
        this.$refs['goodsForm'].validate((valid) => {
          if (valid) {
            addPackage(finalGoods).then(response => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: '添加成功'
              })
              const responseData = response.data.data
              const packageId = responseData
              this.$router.push({ path: '/goods/detailPackage?id=' + packageId })
            }).catch(response => {
              MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
                confirmButtonText: this.$t('Confirm'),
                type: 'error'
              })
            })
          }
        })

      },
      changeVipPrice(){
        this.vipPriceForm = {
          silverVipPrice: !this.productForm.sellPrice?0:(this.productForm.sellPrice * 0.01).toFixed(2),
          goldVipPrice: !this.productForm.sellPrice?0:(this.productForm.sellPrice * 0.02).toFixed(2),
          platinumVipPrice: !this.productForm.sellPrice?0:(this.productForm.sellPrice * 0.04).toFixed(2),
          diamondVipPrice: !this.productForm.sellPrice?0:(this.productForm.sellPrice * 0.1).toFixed(2)
        }
      },
      handleSpecRemove: function() {
        this.specForm.picUrl = undefined
      },
      handleGoodsPicRemove: function() {
        this.packageForm.packageImg = undefined

        // 上传成功后，手动验证一次表单
        this.$refs.goodsForm.validateField('packageImg');
      },
      filterTaxType(type){
        if(type == 1){
          return this.$t('国税')
        }else if(type == 2){
          return this.$t('省税')
        }else if(type == 3){
          return this.$t('地方税')
        }
      },
      handleAccessoryMerChange(){
        let m = this.merchandise.find(item=>{
          if(item.id == this.accessoryForm.merchandiseId){
            this.accessoryForm.name = m.name
            this.accessoryForm.price = m.sellingPrice
            return item
          }
        })

      }
    }
  }
</script>


<style>
  .el-card {
    margin-bottom: 10px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
  .avatar-uploader__status_label{
    display: block;
    color: red;
  }
</style>
